package com.example.tatil.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.tatil.pojo.Result;
import com.example.tatil.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFiletr implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        //1 获取请求url
        log.info("请求的url:{}",requestURI);
        //2 判断请求url中是否含有login，如果含有，说明是登录操作  ，放行
        if (requestURI.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        //3  获取请求头中的令牌
        String jwt = request.getHeader("token");

        //4 判断令牌是否存在
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为空，返回未登录的信息");
            Result notLogin = Result.error("NOT_LOGIN");
            //手动转换对象 --json
            String jsonString = JSONObject.toJSONString((notLogin));
            response.getWriter().write(jsonString);
            return;
        }

        //解析token
        try {
            JwtUtils.pareseJwt(jwt);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录的错误信息");
            Result notLogin = Result.error("NOT_LOGIN");
            //手动转换对象 --json
            String jsonString = JSONObject.toJSONString((notLogin));
            response.getWriter().write(jsonString);
            return;

        }

        //放行
        log.info("令牌合法，直接放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
